package com.hunttown.mes.service;

import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.ScriptFilterUtils;
import com.hunttown.common.domain.Query;
import com.hunttown.mes.dao.TransportUserDao;
import com.hunttown.mes.domain.TransportUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * created by wangjunfu on 2021-02-25 10:59:15
 */
@Service
public class TransportUserService {

    private final static Logger logger = LoggerFactory.getLogger(TransportUserService.class);

    private final TransportUserDao transportUserDao;
    private final AHelpService helpService;
    private final Cache jedisCache;

    @Autowired
    public TransportUserService(TransportUserDao transportUserDao, AHelpService helpService, Cache jedisCache) {
        this.transportUserDao = transportUserDao;
        this.helpService = helpService;
        this.jedisCache = jedisCache;
    }

    /**
     * 新增
     *
     * @param transportUser 实体对象
     * @return 最新插入id
     */
    public TransportUser insert(TransportUser transportUser) {
        //api接口传进来是有值的
        if (transportUser.getEntId() == null)
            transportUser.setEntId(helpService.getEnterpriseId());
        if (transportUser.getAdminId() == null)
            transportUser.setAdminId(0);
        if (transportUser.getCreateTime() == null)
            transportUser.setCreateTime(new Date());
        if (transportUser.getStopFlag() == null)
            transportUser.setStopFlag(0);
        if (transportUser.getDeleteFlag() == null)
            transportUser.setDeleteFlag(0);

        if (ScriptFilterUtils.xssFilterForDomain(GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(transportUser), TransportUser.class))) {
            return transportUser;
        }
        return transportUserDao.insert(transportUser);
    }

    /**
     * 根据ID修改数据信息
     *
     * @param transportUser 实体对象
     * @return True or False
     */
    public Boolean updateInfoById(TransportUser transportUser) {
        if (transportUser.getEntId() == null) {
            transportUser.setEntId(helpService.getEnterpriseId());
        }
        if (ScriptFilterUtils.xssFilterForDomain(GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(transportUser), TransportUser.class))) {
            return false;
        }
        return transportUserDao.updateInfoById(transportUser);
    }

    /**
     * 根据Query修改数据信息
     *
     * @param query 需要修改的字段 KV 格式
     * @return True or False
     */
    public Boolean updateInfoByQuery(Query query) {
        if (!query.containsKey("w_entId")) {
            query.put("w_entId", helpService.getEnterpriseId());
        }

        if (ScriptFilterUtils.xssFilterForQuery(query)) {
            return false;
        }
        return transportUserDao.updateInfoByQuery(query);
    }

    /**
     * 根据ID获取记录信息
     *
     * @param id 主键id
     * @return 实体对象
     */
    public TransportUser selectById(Integer id) {
        return transportUserDao.selectById(id, helpService.getEnterpriseId());
    }

    public TransportUser selectById(Integer id, Integer entId) {
        return transportUserDao.selectById(id, entId);
    }

    /**
     * 根据query取出一条记录，但是可能有多条记录，取最新的一条。
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象
     */
    public TransportUser selectObjByQuery(Query query) {
        if (query == null || query.size() == 0) {
            return null;
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        List<TransportUser> list = selectByQuery(query);
        if (list == null || list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    /**
     * 根据条件获取List
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象列表
     */
    public List<TransportUser> selectByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return transportUserDao.selectByQuery(query);
    }

    /**
     * 根据条件获取记录总数
     *
     * @param query 查询条件 KV 格式
     * @return 总记录数
     */
    public Long countByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return transportUserDao.countByQuery(query);
    }

    /**
     * 根据ID删除记录信息
     *
     * @param id 主键id
     * @return True or False
     */
    public Boolean deleteById(Integer id) {
        return transportUserDao.deleteById(id, helpService.getEnterpriseId());
    }

    //region //理论上缓存都是配置在应用层，这里配置一个只读缓存。

    /**
     * 先从缓存中获取数据
     * 如果缓存为空，从数据库中获取，并将获取的数据添加到缓存。
     *
     * @param id id
     * @return
     */
    public TransportUser getFromCacheId(Integer id, Integer entId) {
        if (id == null || id <= 0) {
            return null;
        }

        TransportUser obj = jedisCache.oget(KeyConstants.USER_INFO_KEY_ID + id, TransportUser.class);
        if (obj == null) {
            if (entId != null && entId > 0) {
                obj = selectById(id, entId);
            } else {
                obj = selectById(id);
            }

            if (obj != null) {
                jedisCache.oset(KeyConstants.USER_INFO_KEY_ID + id, obj);
            }
        }

        return obj;
    }
    //endregion

    /**
     * 模糊搜索会员
     *
     * @param query 条件
     * @return list
     */
    public List<Map<String, String>> selectSimilarUser(final Query query) {
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }
        if (!query.containsKey("stopFlag")) {
            query.put("stopFlag", 0);
        }
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        return transportUserDao.selectSimilarUser(query);
    }

    //通过管理员ID获取会员ID
    public Integer getUseridByManageid(Integer manageId, Integer entId) {
        Query query = Query.noPage();
        query.put("entId", entId);
        query.put("manageId", manageId);
        query.put("stopFlag", 0);
        query.put("orderBy", "order by id desc");
        TransportUser user = selectObjByQuery(query);
        return user == null ? 0 : user.getId();
    }

    //通过司机ID获取会员ID
    public Integer getUseridByDriverid(Integer driverId, Integer entId) {
        Query query = Query.noPage();
        query.put("entId", entId);
        query.put("driverId", driverId);
        query.put("stopFlag", 0);
        query.put("orderBy", "order by id desc");
        TransportUser user = selectObjByQuery(query);
        return user == null ? 0 : user.getId();
    }

    //以map的形式返回数据
    public List<Map<String, String>> getMapDataByQuery(Query query, String element) {
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }
        return transportUserDao.getMapDataByQuery(query, element);
    }
}